﻿var canvas;
var context;
var canvasWidth = 720;
var canvasHeight = 620;

var colorPurple = "#cb3594";
var colorGreen = "#659b41";
var colorYellow = "#ffcf33";
var colorBrown = "#986928";

var curColor = colorPurple;
var clickColor = new Array();
var clickSize = new Array();
var curSize = "normal";
var clickTool = new Array();
var curTool = "crayon";
var curCursor = "pointer";
var curTexts = 0;
var outlineImage = new Image();
var arrImages = new Array();
var arrTexts = new Array();

var mouseX = 0;
var mouseY = 0;

function prepareCanvas()
{
	//context = document.getElementById('digitalCanvas').getContext("2d");
	var canvasDiv = document.getElementById('canvasDiv');
	canvas = document.createElement('canvas');
	canvas.setAttribute('width', canvasWidth);
	canvas.setAttribute('height', canvasHeight);
	canvas.setAttribute('id', 'canvas');
	canvasDiv.appendChild(canvas);
	if(typeof G_vmlCanvasManager != 'undefined') {
		canvas = G_vmlCanvasManager.initElement(canvas);
	}
	context = canvas.getContext("2d");
	document.body.style.cursor = "crosshair";

	arrTexts.push({
			content : "Làm sao để giành \r\n giải chế truyện \r\n của YouNetMedia",
			x		: 320,
			y		: 250,
			color	: curColor,
			isReady : false,
			isDrag	: false,
	});
	
	arrTexts.push({
			content : "|",
			x		: 20,
			y		: 20,
			color	: curColor,
			isReady : false,
			isDrag	: false,
	});
	
	/*arrTexts.push({
			content : "của YouNetMedia",
			x		: 320,
			y		: 290,
			color	: curColor,
			isReady : false,
			isDrag	: false,
	});
	
	arrTexts.push({
			content : "đây ta?",
			x		: 320,
			y		: 310,
			color	: curColor,
			isReady : false,
			isDrag	: false,
	});*/
	
	arrImages.push({
			image 	: new Image(),
			x		: 100,
			y		: 180,	
			isReady	: false,
			isDrag	: false
	});
		
	var index = arrImages.length-1;
	arrImages[index].image.src = "images/resources/nobita4.jpg";
	arrImages[index].image.onload = function()
	{
		arrImages[index].w 		= this.width;
		arrImages[index].h 		= this.height;
		arrImages[index].isReady	= true;
	}
		
	$('#canvas').mousedown(function(e){
		mouseX = e.pageX - this.offsetLeft;
		mouseY = e.pageY - this.offsetTop;
		
		paint = true;
		
		if(curTool=="dragdrop")
		{
			for(i in arrImages)
			{
				arrImages[i].isDrag = false;
			}
			for(var i = arrImages.length - 1; i >= 0; i--)
			{
				if( (arrImages[i].x < mouseX) &&
					((arrImages[i].x + arrImages[i].w) > mouseX) &&
					(arrImages[i].y < mouseY) &&
					((arrImages[i].y + arrImages[i].h) > mouseY)
				)
				{
					arrImages[i].isDrag = true;
					paint = false;
					break;
				}
			}
		}
		else if(curTool=="text")
		{
			
			for(i in arrTexts)
			{
				arrTexts[i].isDrag = false;
			}
			var canAddText = true;
			for(var i = arrTexts.length - 1; i >= 0; i--)
			{
				if( (arrTexts[i].x <= mouseX) &&
					((arrTexts[i].x + arrTexts[i].w) >= mouseX) &&
					(arrTexts[i].y <= mouseY + 15) &&
					((arrTexts[i].y + arrTexts[i].h) >= mouseY + 15)
				)
				{
					arrTexts[i].isDrag = true;
					canAddText = false;
					document.body.style.cursor = "move";
					paint = false;
					break;
				}
				console.log(arrTexts[i]);
			}
			
			if(canAddText)
			{
				$("#txtText").focus();
				$("#textEditor").dialog('option', 'position', [mouseX,mouseY]);
				$("#textEditor").dialog('open');
			}
		}
		else
		{
			addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
		}
		//redraw();
	});
	
	$('#canvas').mousemove(function(e){
		$("#log").text("e.pageX: " + e.pageX + ", e.pageY: " + e.pageY);
		$("#log1").text("mouseX: " + mouseX + ", mouseY: " + mouseY);
		if(curTool=="dragdrop")
		{
			for(i in arrImages)
			{
				if( arrImages[i].isDrag == true)
				{
					var deltaX = (e.pageX - $(this).offset().left)- mouseX;
					var deltaY = (e.pageY - $(this).offset().top)- mouseY;
					arrImages[i].x += deltaX;
					arrImages[i].y += deltaY;
					mouseX = e.pageX - $(this).offset().left;
					mouseY = e.pageY - $(this).offset().top;
				}
			}
		}
		else if(curTool=="text")
		{
			for(i in arrTexts)
			{
				if( arrTexts[i].isDrag == true)
				{
					var deltaX = (e.pageX - $(this).offset().left)- mouseX;
					var deltaY = (e.pageY - $(this).offset().top)- mouseY;
					arrTexts[i].x += deltaX;
					arrTexts[i].y += deltaY;
					mouseX = e.pageX - $(this).offset().left;
					mouseY = e.pageY - $(this).offset().top;
				}
			}
		}
		else
		{
			if(paint){
				addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
				//redraw();
			}
		}
	});
	
	$('#canvas').mouseup(function(e){
		document.body.style.cursor = curCursor;
		paint = false;
		for(i in arrImages)
		{
			arrImages[i].isDrag = false;
		}
		for(i in arrTexts)
		{
			arrTexts[i].isDrag = false;
		}
	});
	
	$('#canvas').dblclick(function(e){
		if(curTool=="text")
		{
			for(var i = arrTexts.length - 1; i >= 0; i--)
			{
				if( (arrTexts[i].x <= mouseX) &&
					((arrTexts[i].x + arrTexts[i].w) >= mouseX) &&
					(arrTexts[i].y <= mouseY + 15) &&
					((arrTexts[i].y + arrTexts[i].h) >= mouseY + 15)
				)
				{
					arrTexts[i].isSelected = true;
					curTexts = i;
					break;
				}
			}
		}
	});
	
	$('#canvas').attr('tabindex', 0);
	
	$('#canvas').keydown(function(e){
		var charCode = (e.keyCode ? e.keyCode : e.which);

		if(charCode==13)
		{
			arrTexts[1].content += "\n";
		}

		if(charCode !=8)//backspace
		{
			var charStr = fixedFromCharCode(charCode);
			arrTexts[1].content += charStr;
		}

		if(charCode == 8)//backspace
		{
			arrTexts[1].content = arrTexts[1].content.substring(0, arrTexts[1].content.length -1);
			console.log(arrTexts[1].content);
		}

		if(charCode == 231)
		{
			arrTexts[1].content += "ư";
			arrTexts[1].content = arrTexts[1].content.replace("ç","");
		}

		console.log(charCode);

		if(charCode == 46 && curTool == 'text')//delete key
		{
			arrTexts.splice(curTexts, 1);
		}
	});
	
		
	function fixedFromCharCode (codePt) {  
		if (codePt > 0xFFFF) {  
			codePt -= 0x10000;  
			return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 +  
			(codePt & 0x3FF));  
		}  
		else {  
			return String.fromCharCode(codePt);  
		}  
	}  

	$('#canvas').keyup(function(e){
		
	});
	
	var clickX = new Array();
	var clickY = new Array();
	var clickDrag = new Array();
	var paint;

	function addClick(x, y, dragging)
	{
		clickX.push(x);
		clickY.push(y);
		clickDrag.push(dragging);
		clickTool.push(curTool);
		clickColor.push(curColor);
		clickSize.push(curSize);
	}
	
	(function redraw()
	{
		canvas.width = canvas.width; // Clears the canvas
		//context.strokeStyle = "#df4b26";
		context.lineJoin = "round";
		context.lineWidth = 5;
		var radius = 0;	
		
		context.fillStyle = "#FFFFFF";
		context.fillRect(0, 0, canvasWidth, canvasHeight);
		
		for(i in arrImages)
		{
			context.drawImage(arrImages[i].image,arrImages[i].x,arrImages[i].y);
			if(arrImages[i].isDrag)
			{
				context.lineWidth = 1;
				context.strokeRect(arrImages[i].x,arrImages[i].y,arrImages[i].w+2,arrImages[i].h+2);
			}
		}

		for(j in arrTexts)
		{
			context.font = "14px Arial";
			context.fillStyle = arrTexts[j].color;

			arrTexts[j].content = arrTexts[j].content.replace(new RegExp( "\\n", "g" ),'<br/>');

			var multilines = arrTexts[j].content.split("<br/>");

			yOffset = 0;

			for(line in multilines)
			{	
				context.fillText(multilines[line], arrTexts[j].x, arrTexts[j].y+yOffset);
				yOffset+=16;
			}

			var textObj = context.measureText(arrTexts[j].content);
			arrTexts[j].w = textObj.width;
			arrTexts[j].h = 15;
			
			
			if(arrTexts[j].isSelected == true)
			{
				context.strokeStyle = "#df4b26";
				context.lineWidth = 1;
				context.strokeRect(arrTexts[j].x,arrTexts[j].y-15,arrTexts[j].w+3,arrTexts[j].h+3);
			}
				
			if(arrTexts[j].isDrag)
			{
				context.lineWidth = 1;
				context.strokeRect(arrTexts[j].x,arrTexts[j].y-15,arrTexts[j].w+3,arrTexts[j].h+3);
			}
		}
		
		for(var i=0; i < clickX.length; i++)
		{
			if(clickSize[i] == "small")
			{
				radius = 2;
			}
			else if(clickSize[i] == "normal")
			{
				radius = 5;
			}
			else if(clickSize[i] == "large")
			{
				radius = 10;
			}
			else if(clickSize[i] == "huge")
			{
				radius = 20;
			}
			else
			{
				alert("Error: Radius is zero for click " + i);
				radius = 0;	
			}
			
			context.beginPath();
			
			if(clickDrag[i] && i)
			{
				context.moveTo(clickX[i-1], clickY[i-1]);
			}
			else
			{
				context.moveTo(clickX[i]-1, clickY[i]);
			}
			
			if(clickTool[i] == 'eraser')
			{
				context.strokeStyle = 'white';
			}
			else
			{
				context.strokeStyle = clickColor[i];
			}
			
			context.globalAlpha = 1;
			context.lineTo(clickX[i], clickY[i]);
			context.lineWidth = radius;
			context.closePath();
			context.stroke();
			//context.drawImage(outlineImage, 0, 0, 267, 210);
		}
		
		setTimeout(redraw,50);
	})();
	
	$('.brushSize').click(function(){
		curSize = $(this).attr('title');
	});
	
	$('#btnEraser').click(function(){
		curTool = "eraser";
		$(this).css('background','url("images/earser_selected.gif")');
		$('.tool:not(#btnEraser)').removeAttr('style');
		document.body.style.cursor = "pointer";
		curCursor = "pointer";
	});
	
	$('#btnCrayon').click(function(){
		curTool = "crayon";
		$(this).css('background','url("images/crayon_selected.jpg")');
		$('.tool:not(#btnCrayon)').removeAttr('style');
		document.body.style.cursor = "crosshair";
		curCursor = "crosshair";
	});
	
	$('#btnText').click(function(){
		curTool = "text";
		$(this).css('background','url("images/text_tool_selected.jpg")');
		$('.tool:not(#btnText)').removeAttr('style');
		document.body.style.cursor = "text";
		curCursor = "text";
		//$( "#textEditor" ).dialog('open');
	});
	
	$('#btnDrag').click(function(){
		curTool = "dragdrop";
		$(this).css('background','url("images/cursor_drag_arrow_selected.png")');
		$('.tool:not(#btnDrag)').removeAttr('style');
		document.body.style.cursor = "move";
		curCursor = "move";
	});
	
	$('#btnTextOK').click(function(){
		arrTexts.push({
			content 	: $('#txtText').val(),
			x			: mouseX,
			y			: mouseY,
			color		: curColor,
			isReady 	: false,
			isDrag		: false,
			isSelected	: false,
		});
		$('#txtText').val(''),
		$( "#textEditor" ).dialog('close');
	});
	
	$('.images').click(function(){
		arrImages.push({
			image 	: new Image(),
			x		: 0,
			y		: 0,	
			isReady	: false,
			isDrag	: false
		});
		var index = arrImages.length-1;
		arrImages[index].image.src = "images/"+$(this).val();
		arrImages[index].image.onload = function()
		{
			arrImages[index].w 		= this.width;
			arrImages[index].h 		= this.height;
			arrImages[index].isReady	= true;
		}
	});
	
	$('.colorItem').css('cursor','pointer');
	$('.colorItem').click(function(){
		curColor = $(this).attr('title');
	});
	
	$('#btnSave').click(function(){
		var img = canvas.toDataURL("image/png");
		document.write('<img src="'+img+'"/>');
	});
	
	$('#btnNew').click(function(){
		context.save();
		// Use the identity matrix while clearing the canvas
		context.setTransform(1, 0, 0, 1, 0, 0);
		context.clearRect(0, 0, canvas.width, canvas.height);
		// Restore the transform
		context.restore();
		clickX = new Array();
		clickY = new Array();
		arrImages = new Array();
		arrTexts = new Array();
	});
}

